//
//  RegisterViewController.m
//  老司机发车了
//
//  Created by 斌 on 16/8/6.
//  Copyright © 2016年 斌. All rights reserved.
//

#import "RegisterViewController.h"
#import "LoginViewController.h"



@interface RegisterViewController ()<UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet UIImageView *backimg;

// 昵称
@property (strong, nonatomic) UITextField *nickname;
// 用户名
@property (strong, nonatomic) UITextField *userName;
// 密码
@property (strong, nonatomic) UITextField *password;
// 确认密码
@property (strong, nonatomic) UITextField *confirmPassword;
// 电话号
@property (strong, nonatomic) UITextField *phoneNum;
// 验证码
@property (strong, nonatomic) UITextField *verification;
// 获取验证码按钮
@property (strong, nonatomic) UITextField *getVerification;
// 注册按钮
@property (strong, nonatomic) UIButton *registerButton;
// 登陆按钮
@property (strong, nonatomic) UIButton *loginButton;
// 取消按钮
@property (strong, nonatomic) UIButton *cancelButton;
// 滚图
@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;


@end

@implementation RegisterViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationItem.title = @"注册账号";
    
    self.backimg.image = [UIImage imageNamed:@"登陆界面.jpg"];
    
    self.scrollView.contentSize = CGSizeMake(kScreenWidth, 800);
    self.userName.delegate = self;
    
    NSArray *labelArr = @[@"昵称",@"用户名",@"密码",@"确认密码",@"手机号",@"验证码"];
    // 循环创建label
    for (int i = 0; i < 6; i++) {
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(20, 60 * i + 50, 100, 30)];
        label.text = labelArr[i];
        [self.scrollView addSubview:label];
    }
    
    self.nickname = [[UITextField alloc] initWithFrame:CGRectMake(120, 50, 200, 30)];
    self.nickname.backgroundColor = [UIColor whiteColor];
    [self.scrollView addSubview:_nickname];
    
    self.userName = [[UITextField alloc] initWithFrame:CGRectMake(120, 110, 200, 30)];
    self.userName.backgroundColor = [UIColor whiteColor];
    [self.scrollView addSubview:_userName];
    
    self.password = [[UITextField alloc] initWithFrame:CGRectMake(120, 170, 200, 30)];
    self.password.backgroundColor = [UIColor whiteColor];
    [self.scrollView addSubview:_password];
    
    self.confirmPassword = [[UITextField alloc] initWithFrame:CGRectMake(120, 230, 200, 30)];
    self.confirmPassword.backgroundColor = [UIColor whiteColor];
    [self.scrollView addSubview:_confirmPassword];
    
    self.phoneNum = [[UITextField alloc] initWithFrame:CGRectMake(120, 290, 200, 30)];
    self.phoneNum.backgroundColor = [UIColor whiteColor];
    [self.scrollView addSubview:_phoneNum];
    
    // 获取验证码按钮
    UIButton *getVerification = [UIButton buttonWithType:UIButtonTypeCustom];
    getVerification.frame = CGRectMake(120, 320, 100, 30);
    getVerification.centerX = _phoneNum.centerX;
    [getVerification setTitle:@"获取验证码" forState:UIControlStateNormal];
    [getVerification setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    [getVerification addTarget:self action:@selector(getVerificationAction) forControlEvents:UIControlEventTouchUpInside];
    [self.scrollView addSubview:getVerification];
    
    
    self.verification = [[UITextField alloc] initWithFrame:CGRectMake(120, 350, 200, 30)];
    self.verification.backgroundColor = [UIColor whiteColor];
    [self.scrollView addSubview:_verification];
    
    // 注册按钮
    self.registerButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.registerButton.frame = CGRectMake(20, _verification.endY + 50, 100, 30);
    [self.registerButton addTarget:self action:@selector(registerAction) forControlEvents:UIControlEventTouchUpInside];
    [self.registerButton setTitle:@"注册" forState:UIControlStateNormal];
    [self.registerButton setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
    [self.scrollView addSubview:_registerButton];
    
    // 登陆按钮
    self.loginButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.loginButton.frame = CGRectMake(kScreenWidth - 120, _verification.endY + 50, 100, 30);
    [self.loginButton addTarget:self action:@selector(loginAction) forControlEvents:UIControlEventTouchUpInside];
    [self.loginButton setTitle:@"登陆" forState:UIControlStateNormal];
    [self.loginButton setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
    [self.scrollView addSubview:_loginButton];
    
    // 取消按钮
    self.cancelButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.cancelButton.frame = CGRectMake(0, _verification.endY + 100, 100, 30);
    self.cancelButton.centerX = kScreenWidth / 2;
    [self.cancelButton addTarget:self action:@selector(cancelAction) forControlEvents:UIControlEventTouchUpInside];
    [self.cancelButton setTitle:@"取消注册" forState:UIControlStateNormal];
    [self.cancelButton setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
    [self.scrollView addSubview:_cancelButton];

    
   
}

// 点击textfield触发事件
-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    NSLog(@"点击");
    return  YES;
}

// textfield结束输入
- (void)textFieldDidEndEditing:(UITextField *)textField {
    NSLog(@"输入结束");
}

// 获取验证码按钮方法
- (void)getVerificationAction {
    
}

// 注册按钮方法
- (void)registerAction {
    
    NSString *nickname = self.nickname.text;
    if (nickname.length == 0 || nickname.length > 6) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"警告" message:@"昵称不可为空且不能大于6个字" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *sure = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        [alert addAction:sure];
        [self presentViewController:alert animated:YES completion:nil];
        return;
    }
    
    if (self.userName.text.length < 6 || self.userName.text.length > 15) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"警告" message:@"用户名不可小于6位且不能大于15位" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *sure = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        [alert addAction:sure];
        [self presentViewController:alert animated:YES completion:nil];
        return;
    }
    
    if (self.password.text.length < 6 || self.userName.text.length > 15) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"警告" message:@"密码不可小于6位且不能大于15位" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *sure = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        [alert addAction:sure];
        [self presentViewController:alert animated:YES completion:nil];
        return;
    }
    
    if (![self.confirmPassword.text isEqualToString:self.password.text]) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"警告" message:@"两次密码不一致" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *sure = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        [alert addAction:sure];
        [self presentViewController:alert animated:YES completion:nil];
        return;
    }
    
    BmobQuery   *bquery = [BmobQuery queryWithClassName:@"User"];
    // 添加约束条件
    [bquery whereKey:@"username" equalTo:_userName.text];
    //查找GameScore表的所有符合约束条件的数据
    [bquery findObjectsInBackgroundWithBlock:^(NSArray *array, NSError *error) {
        if (array.count > 0) {
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"警告" message:@"用户名已存在" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *sure = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                
            }];
            [alert addAction:sure];
            [self presentViewController:alert animated:YES completion:nil];
            return;
        } else {
            //在GameScore创建一条数据，如果当前没GameScore表，则会创建GameScore表
            BmobObject  *user = [BmobObject objectWithClassName:@"User"];
            NSData *data;
            UIImage *img = [UIImage imageNamed:@"登录.jpg"];
            if (UIImagePNGRepresentation(img) == nil) {
                
                data = UIImageJPEGRepresentation(img, 1);
                
            } else {
                
                data = UIImagePNGRepresentation(img);
            }
            
            BmobFile *file = [[BmobFile alloc] initWithFileName:@"image.jpg" withFileData:data];
            [file saveInBackground:^(BOOL isSuccessful, NSError *error) {
                //如果文件保存成功，则把文件添加到image列
                if (isSuccessful) {
                    [user setObject:file forKey:@"image"];
                    //            [user saveInBackground];
                    [user setObject:file.url forKey:@"imgUrl"];
                    //打印file文件的url地址
                    NSLog(@"file1 url %@",file.url);
                    
                    // 上传昵称
                    [user setObject:_nickname.text forKey:@"nickname"];
                    // 上传用户名
                    [user setObject:_userName.text forKey:@"username"];
                    // 上传密码
                    [user setObject:_password.text forKey:@"password"];
                    // 上传手机号
                    [user setObject:_phoneNum.text forKey:@"phoneNum"];
                    // 上传等级
                    [user setObject:@"新手上路" forKey:@"level"];
                    // 上传签名
                    [user setObject:@"" forKey:@"sign"];
                    //设置cheatMode为NO
                    //    [user setObject:[NSNumber numberWithBool:NO] forKey:@"cheatMode"];
                    //设置age为18
                    //    [user setObject:[NSNumber numberWithInt:18] forKey:@"age"];
                    
                    //异步保存到服务器
                    [user saveInBackgroundWithResultBlock:^(BOOL isSuccessful, NSError *error) {
                        if (isSuccessful) {
                            
                            //创建成功后会返回objectId，updatedAt，createdAt等信息
                            //创建对象成功，打印对象值
                            NSLog(@"%@",user);
                            
                            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"恭喜您注册成功" preferredStyle:UIAlertControllerStyleAlert];
                            UIAlertAction *sure = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                                LoginViewController *loginVC = [[LoginViewController alloc] init];
                                loginVC.name = _userName.text;
                                loginVC.pass = _password.text;
                                [self.navigationController pushViewController:loginVC animated:YES];
                            }];
                            [alert addAction:sure];
                            [self presentViewController:alert animated:YES completion:nil];
                        } else if (error){
                            //发生错误后的动作
                            NSLog(@"%@",error);
                        } else {
                            NSLog(@"Unknow error");
                        }
                    }];
                    
                }else{
                    //进行处理
                    NSLog(@"dfsfs");
                }
            }];
        }
    }];
}

// 登陆按钮方法
- (void)loginAction {
    LoginViewController *loginVC = [[LoginViewController alloc] init];
    
    [self.navigationController pushViewController:loginVC animated:YES];
    
}

// 取消按钮方法
- (void)cancelAction {
    [self dismissViewControllerAnimated:YES completion:nil];
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
